<template>
  <div class="selector" v-focus>
    <TSelectorInput
      :placeholder="placeholder"
      :value="inputValue"
      @searchOptions="searchOptions"
    />
    <TSelectorMenu
      :data="data"
      @setItemValue="setItemValue"
      :searchValue="searchValue"
    />
  </div>
</template>

<script>

import { focus } from '../../direactives/index.js';

import TSelectorInput from './TSelectorInput.vue';
import TSelectorMenu from './TSelectorMenu.vue';

import { reactive, toRefs } from 'vue';

export default {
  name: 'TSelector',
  props: {
    data: Array,
    placeholder: String
  },
  directives: {
    focus
  },
  components: {
    TSelectorInput,
    TSelectorMenu
  },
  setup (props, ctx) {
    
    const state = reactive({
      inputValue: '',
      searchValue: ''
    })

    const setItemValue = (item) => {
      state.inputValue = item.text;
      ctx.emit('setItemValue', item.value);
    }

    const searchOptions = (value) => {
      state.searchValue = value;
    }

    return {
      setItemValue,
      searchOptions,
      ...toRefs(state)
    }
  }
}
</script>

<style lang="scss" scoped>
  .selector {
    width: 300px;
    position: relative;
  }
</style>